<?php namespace App\Http\Controllers\Api\Admin;

use App\Course;
use App\Http\Controllers\Controller;
use App\Http\Services\AdminManager;
use App\Http\Services\ToolsManager;
use App\IntegralDetail;
use App\OrderItem;
use App\Orders;
use App\SystemGroup;
use App\User;
use App\UserGroup;
use App\UserGroupXUser;
use App\UserInfo;
use App\VipInfo;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Exception;

class OrderController extends Controller
{
    public function delOrder(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $orderId = $request->input('id',0);

        $thatOrder = Orders::whereId($orderId)->first();
        if(!$thatOrder){
            return response()->json(['level' => 'error','message' => '订单不存在']);
        }
        if($thatOrder->referrer != 'manager'){
            return response()->json(['level' => 'error','message' => '用户自主订单不允许删除']);
        }

        $thatOrder->delete();

        return response()->json(['level' => 'success','message' => '删除成功']);
    }

    public function setOrder(Request $request){
        /** @var User $adminUser */
        $adminUser = AdminManager::isLogin($request);
        if(!$adminUser)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $remark             = $request->input('remark','');
        $course_id          = $request->input('course_id',0);
        $vipType            = $request->input('vip_type','');
        $phone              = $request->input('phone') ?? '';
        $realname           = $request->input('realname') ?? '';
        $province           = $request->input('province') ?? '';
        $city               = $request->input('city') ?? '';
        $area               = $request->input('area') ?? '';
        $sex                = $request->input('sex') ?? '';
        $isPay              = !is_null($request->input("is_pay")) ? $request->input("is_pay") : 0;
        $payWay             = !is_null($request->input("pay_way")) ? $request->input("pay_way") : 'cash';
        $payTime            = $request->input("pay_time");
        $payAmount          = $request->input("pay_amount");

        /** 创建单号 */
        $orderNum = ToolsManager::makeBillNum();
        while(true){
            $isOrders = Orders::whereOrderNum($orderNum)->first();
            if($isOrders){
                $orderNum = ToolsManager::makeBillNum();
            }else{
                break;
            }
        }

        if(!$phone)
            return response()->json(['level' => 'error','message' => '请填写手机号']);

        if(!$province || !$city || !$area)
            return response()->json(['level' => 'error','message' => '请选择所在地区']);

        try {
            $thatUser = User::wherePhone($phone)->first();

            $userId = $thatUser ? $thatUser->id : 0;

            DB::beginTransaction();
            /** 处理课程 */
            $thisOrder = new Orders();
            $thisOrder->order_num = $orderNum;
            $thisOrder->user_id = $userId;
            $thisOrder->remark = $remark ? $remark : '';
            $thisOrder->province = $province;
            $thisOrder->city = $city;
            $thisOrder->area = $area;
            $thisOrder->phone = $phone;
            $thisOrder->sex = $sex;
            $thisOrder->realname = $realname;
            $thisOrder->referrer = "manager";
            $thisOrder->save();

            $total_original_price = 0;
            $total_pay_amount = 0;
            $total_pay_integral = 0;
            $total_vip_num = 0;

            //直接下单
            /** @var Course $thisCourse */
            $thisCourse=Course::whereId($course_id)->lockForUpdate()->first();
            if (!$thisCourse){
                DB::rollBack();
                return response()->json(['level'=>'error','message'=>'此服务不存在']);
            }
            if ($thisCourse->status!=1){
                DB::rollBack();
                return response()->json(['level'=>'error','message'=>"服务 $thisCourse->name 暂时不可购买"]);
            }


            $thisCourse->selling_num     =$thisCourse->selling_num + 1;
            $thisCourse->save();

            $coursePrice = $thisCourse->show_price;

            $orderItem                   = new OrderItem();
            $orderItem->order_id         = $thisOrder->id;
            $orderItem->user_id          = $userId;
            $orderItem->item_num         = $thisOrder->order_num.'#'.rand(1000,9999);
            $orderItem->course_id        = $thisCourse->id;
            $orderItem->original_price   = $thisCourse->show_price;
            $orderItem->discount_price   = $coursePrice;
            $orderItem->num              = 1;
            $orderItem->total_amount     = round($orderItem->discount_price *  $orderItem->num ,2);
            $orderItem->save();


            $total_pay_amount            = $total_pay_amount + $orderItem->total_amount;
            $total_original_price        = $thisCourse->show_price;

            if(!is_null($payAmount)){
                $total_pay_amount     = $payAmount;
                $total_original_price = $payAmount;
            }

            //继续处理订单
            $thisOrder->original_price   = $total_original_price;
            $thisOrder->pay_amount       = $total_pay_amount;
            $thisOrder->pay_integral     = $total_pay_integral;
            $thisOrder->pay_vip_num      = $total_vip_num;
            $thisOrder->is_pay           = $isPay;
            $thisOrder->pay_time         = $payTime;
            $thisOrder->pay_way          = $payWay;

            if($thisOrder->is_pay == 1){
                $thisOrder->is_success = 1;
                $thisOrder->review = 1;
            }

            $thisOrder->save();

            DB::commit();
        }catch (Exception $exception){
            DB::rollBack();
            return response()->json([
                'level'     =>'error',
                'message'   =>$exception->getMessage(),
                'data'      =>$exception->getTrace()
            ]);
        }

        return response()->json([
            'level'     =>'success',
            'message'   =>'设置成功',
            'data'      =>['order'=>$thisOrder,'order_item'=>OrderItem::whereOrderId($thisOrder->id)->get()]
        ]);
    }
}
